import {defineStore} from 'pinia'
import request from '@/request'
import router from '@/router'
import {handleLogout} from '../api/logout.js'
import {useSkeletonStore} from '@/stores/skeleton.js'
import { changeRoleIdMenus } from '../api/sysroles.js'
import {useMenuTabStore} from '@/stores/menuTab.js'

export const useUserStore = defineStore('user', {
    // 定义状态
    state: () => ({
        routerLoaded: false,
        user: {},
        username: '',
        userId: '',
        token: '',
        currRoleId: 0,
        isCollapse: false,
        currRoleName: "",
        roles: [],
        permissions: [],
        // 路由菜单，用来接收服务端传递过来的菜单数据
        menuTree: [],
        // 系统列表
        systemList: [{sysname: "默认", id: 0,defaultFlag:0}]
    }),

    // 就是一种计算属性的机制，定义的是函数，使用的是属性就相当于computed
    getters: {
        isLogin(state) {
            return state.token ? true : false
        },

        roleName(state) {
            return state.roles && state.roles.map(r => r.name).join(",")
        },

        permissionCode(state) {
            return state.permissions && state.permissions.map(r => r.code).join(",")
        },

        permissionPath(state) {
            return state.permissions && state.permissions.map(r => r.path)
        }
    },

    // 定义动作
    actions: {
        // 改变用户角色的时候把对应菜单和权限查询出来，进行覆盖
        async handlePianaRole(roleId, roleName) {
            if (roleId > 0 && roleId != this.currRoleId) {
                this.currRoleId = roleId
                this.currRoleName = roleName;
            }

            // 获取到导航菜单，切换以后直接全部清空掉
            const menuTabStore = useMenuTabStore();
            menuTabStore.clear()

            // 请求服务端--根据切换的角色找到角色对应的权限和菜单
            const resp = await changeRoleIdMenus({roleId: this.currRoleId})
            // 对应的权限和菜单进行覆盖
            this.permissions = resp.data.permissions
            this.menuTree = resp.data.roleMenus.sort((a, b) => a.sort - b.sort)
            if (roleId > 0 && this.menuTree && this.menuTree.length > 0) {
                // 激活菜单中的第一个路由
                router.push(this.menuTree[0]?.path)
            }
        },

        /* 设置token */
        setToken(newtoken) {
            this.token = newtoken
        },

        /* 获取token*/
        getToken() {
            return this.token
        },

        /* 登出*/
        async logout() {
            // 清除状态信息
            this.token = ''
            this.user = {}
            this.username = ''
            this.userId = ''
            this.roles = []
            this.systemList = [{sysname: "默认", id: 0,defaultFlag:0}]
            this.permissions = []
            this.menuTree = []
            // 清除自身的本地存储
            localStorage.removeItem("mayan-kva-language")
            localStorage.removeItem("mayan-pinia-userstore")
            sessionStorage.removeItem("mayan-pinia-skeleton")
            localStorage.removeItem("isWhitelist")
            // 把骨架屏的状态恢复到true的状态
            useSkeletonStore().setLoading(true)
            // 然后跳转到登录
            router.push("/login")
            // 执行服务端退出
            try {
                await handleLogout()
            }catch (ex){
                console.log("退出失败......")
            }
        },

        /* 登录*/
        async toLogin(loginUser) {
            // 查询用户信息，角色，权限，角色对应菜单
            const resp = await request.post("login/toLogin", loginUser, {noToken: true})
            // 这个会回退，回退登录页
            var {sysUsers, accessToken, roles, permissions, menus, adminSystems} = resp.data
            // 登录成功以后获取到菜单信息, 这里要调用一
            this.menuTree =  menus
            // 把数据放入到状态管理中
            this.user = sysUsers
            this.userId = sysUsers.id
            this.username = sysUsers.username
            this.token = accessToken
            this.roles = roles || []
            this.permissions = permissions || []
            this.systemList = adminSystems || []
            this.currRoleId = roles && roles.length > 0 ? roles[0].id : 0
            this.currRoleName = roles && roles.length > 0 ? roles[0].roleName : ""
            return Promise.resolve(resp)
        }
    },
    persist: {
        key: 'mayan-pinia-userstore',
        storage: localStorage,//sessionStorage
    }
})